package com.kuaimacode.kframework.api.controller.master;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.api.controller.BaseController;
import com.kuaimacode.kframework.api.service.*;
import com.kuaimacode.kframework.api.service.category.AgentServService;
import com.kuaimacode.kframework.api.service.invite.InviteService;
import com.kuaimacode.kframework.api.service.sys.SysOpLogService;
import com.kuaimacode.kframework.api.service.user.OrderDispatchService;
import com.kuaimacode.kframework.api.service.user.OrderService;
import com.kuaimacode.kframework.api.vo.request.*;
import com.kuaimacode.kframework.api.vo.response.*;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.component.ComponentUtil;
import com.kuaimacode.kframework.component.SmsRecordService;
import com.kuaimacode.kframework.component.SmsSendService;
import com.kuaimacode.kframework.constants.MasterConstants;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.enums.AppletsPushTemplateEnum;
import com.kuaimacode.kframework.enums.ProtocolTypeEnum;
import com.kuaimacode.kframework.exception.ErrorEnum;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgent;
import com.kuaimacode.kframework.mybatis.models.category.AgentServ;
import com.kuaimacode.kframework.mybatis.models.finance.AgentAccountDetail;
import com.kuaimacode.kframework.mybatis.models.invite.Invite;
import com.kuaimacode.kframework.mybatis.models.master.MasterAccitityData;
import com.kuaimacode.kframework.mybatis.models.master.MasterMessage;
import com.kuaimacode.kframework.mybatis.models.master.MasterOrderAccitity;
import com.kuaimacode.kframework.mybatis.models.master.UserMaster;
import com.kuaimacode.kframework.mybatis.models.masterscore.MasterScoreDetails;
import com.kuaimacode.kframework.mybatis.models.masterscore.MasterScoreLevel;
import com.kuaimacode.kframework.mybatis.models.score.AdminScoreManagentment;
import com.kuaimacode.kframework.mybatis.models.sys.Dict;
import com.kuaimacode.kframework.mybatis.models.sys.SysOpLog;
import com.kuaimacode.kframework.mybatis.models.sysparam.SysParam;
import com.kuaimacode.kframework.mybatis.models.user.*;
import com.kuaimacode.kframework.service.DictService;
import com.kuaimacode.kframework.util.*;
import com.kuaimacode.kframework.weixin.AppletsTemplateData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/master")
@SessionAttributes("user")
@Api(tags = "师傅", description = "师傅相关api")
@EnableAsync
public class MasterRestController extends BaseController {

    private static final String pic = "https://static.haokur.com/home_master_img.png";

    private static final String name = "师傅";

    private static final String CONSTANTS_1 = "1";

    private static final String CONSTANTS_0 = "0";

    private static final String CONSTANTS_2 = "2";

    private static final String RECIVED_FAIL = "订单已被其他师傅接单";


    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SmsSendService smsSendService;
    @Autowired
    private SmsRecordService recordService;
    @Autowired
    private MasterScoreDetailsService detailsService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private UserMasterService masterService;
    @Autowired
    private SysAgentCategoryCfgService cfgService;
    @Autowired
    private UserCertifacateService certifacateService;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private ContentService contentService;
    @Autowired
    private MasterOrderAccitityService accitityService;

    @Autowired
    private SysMessageService sysMessageService;

    @Autowired
    private ScoreManagentmentService scoreManagentmentService;


    @Autowired
    private OrderDispatchService orderDispatchService;

    @Autowired
    private UserAccountDetailService accountDetailService;

    @Autowired
    private AgentServService agentServService;

    @Autowired
    private AgentService agentService;

    @Autowired
    private AgentAccountDetailService agentAccountDetailService;


    @Autowired
    private ComponentUtil componentUtil;

    @Autowired
    private SysOpLogService opLogService;

    @Autowired
    private InviteService inviteService;
    @Autowired
    private SysParamService sysParamService;

    @Autowired
    private DictService dictService;



    private static Logger logger = LoggerFactory.getLogger(MasterRestController.class);


//    private static Cache dictCache = EhCacheUtil.getDictCache();


    /************************************师傅搜索********************************************/
    @ApiOperation(value = "师傅搜索(万能帮办)-维修过的师傅", notes = "维修过的师傅")
    @PostMapping("/servicedMaster")
    @ApiImplicitParam(name = "masterServicedReq", value = "masterServicedReq实体服务品类传code值", required = true, dataType = "MasterServicedReq")
    public JsonResult<List<MasterResp>> servicedMaster(@Valid @RequestBody MasterServicedReq masterServicedReq) {
        Long userId = getUserId();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("status", Constant.OrderStatusEnum.OK.getCode());
        initPageParam(masterServicedReq.getPageNum(), masterServicedReq.getPageSize(), null, masterServicedReq);
        List<Order> orders = orderService.list(queryWrapper);
        List<MasterResp> masterResps = new ArrayList<>();
        MasterResp masterResp = new MasterResp();
        if (CollectionUtils.isNotEmpty(orders)) {
            Map<Long, List<Order>> orderMap = orders.
                    parallelStream().
                    collect(Collectors.
                            groupingBy(Order::getMasterId));
            orderMap.forEach((k,v)->{
                Map<String, String> map = masterService.getMasterServiceType(k);
                List<Order> masterOrders = orderMap.get(k);
                Order order = masterOrders.get(0);
                map.forEach((key,value)->{
                    AgentServ agentServ = agentServService.queryServByAgentIdAndCode(order.getAgentId(),key,masterServicedReq.getServiceClass());
                    if (agentServ!=null){
                        UserMaster master = masterService.getUserMasterByUserId(k);
                        masterResp.setMasterId(String.valueOf(k));
                        User certifacate = userService.getById(k);
                        masterResp.setMasterName(certifacate != null && StringUtils.isNotEmpty(master.getMasterName()) ? master.getMasterName() :name);
                        masterResp.setStarLevel(getMasterStar(master.getUserId()));
                        if(certifacate==null||StringUtils.isEmpty(certifacate.getAvatarUrl())){
                            masterResp.setHeadPic(pic);
                        }else{
                            masterResp.setHeadPic(uploadService.getPicUrlPath(certifacate.getAvatarUrl()));
                        }
                        masterResps.add(masterResp);
                    }
                });

            });
        }
        if (CollectionUtils.isNotEmpty(masterResps)) {
            return JsonResult.success(parsePage(masterResps,masterServicedReq.getPageNum(),masterServicedReq.getPageNum()));
        } else {
            return JsonResult.success(new PageInfo<>(masterResps));
        }
    }


    @ApiOperation(value = "师傅搜索(万能帮办)-附近师傅", notes = "附近师傅")
    @PostMapping("/masterSeachList")
    @ApiImplicitParam(name = "masterReq", value = "masterReq实体", required = true, dataType = "MasterReq")
    public JsonResult<PageInfo<MasterResp>> masterSeachList(@Valid @RequestBody MasterReq masterReq) {
        if (StringUtils.isEmpty(masterReq.getDistance())) {
            masterReq.setDistance(String.valueOf(10));
        } else {
            masterReq.setDistance(String.valueOf(Integer.parseInt(masterReq.getDistance())));
        }
        initPageParam(masterReq.getPageNum(), masterReq.getPageSize(), masterReq, null);
        List<MasterResp> masterResps = masterService.getNearMasterBySkillType(masterReq, "2");
        if (CollectionUtils.isNotEmpty(masterResps)) {
            for (MasterResp resp : masterResps) {
                User certifacate = userService.getById(getUserId());
                if(certifacate==null||StringUtils.isEmpty(certifacate.getAvatarUrl())){
                    resp.setHeadPic(pic);
                }else{
                    resp.setHeadPic(uploadService.getPicUrlPath(certifacate.getAvatarUrl()));
                }                resp.setMasterName(certifacate != null && StringUtils.isNotEmpty(resp.getMasterName()) ? resp.getMasterName() : name);
            }
        }
        if (CollectionUtils.isNotEmpty(masterResps)) {
            return JsonResult.success(parsePage(masterResps,masterReq.getPageNum(),masterReq.getPageSize()));
        } else {
            return JsonResult.success(new PageInfo<>(masterResps));
        }

    }

    private PageInfo<MasterResp> parsePage(List<MasterResp> masterResps,Integer pageNum,Integer pageSize){
        PageUtils<MasterResp> listPageUtil = new PageUtils<MasterResp>(masterResps, pageNum, pageSize);
        List<MasterResp> pagedList = listPageUtil.getPagedList();
        PageInfo<MasterResp> masterRespPageInfo = new PageInfo<MasterResp>(pagedList);
        masterRespPageInfo.setPageNum(pageNum);
        masterRespPageInfo.setPages(listPageUtil.getTotalPage());
        masterRespPageInfo.setPageSize(pageSize);
        masterRespPageInfo.setSize(listPageUtil.getTotalCount());
        masterRespPageInfo.setStartRow(listPageUtil.getPageindex());
        masterRespPageInfo.setEndRow(listPageUtil.getEndindex());
        return masterRespPageInfo;
    }

    @ApiOperation(value = "获取附近骑手", notes = "获取附近骑手")
    @PostMapping(value = "/getNearRider")
    public JsonResult<LocationResp> getNearRider(@Valid @RequestBody LocationReq locationReq) {
        String agentId = null;
        if (locationReq.getAgentId()!=0&&locationReq.getAgentId()>0){
            agentId = String.valueOf(locationReq.getAgentId());
        }
        List<LocationResp> resps = masterService.getNearRider(locationReq,agentId );
        return JsonResult.success(resps);
    }

    /************************************师傅搜索********************************************/


    /************************************认证流程start********************************************/

    @ApiOperation(value = "师傅认证-检验该手机号是否已认证为师傅或正在认证", notes = "检验该手机号是否已认证为师傅或正在认证接口，{phoneNumber:手机号码}必传")
    @PostMapping(value = "/validatePhoneNumber/{phoneNumber}")
    @ApiImplicitParam(name = "phoneNumber", value = "用户手机号", required = true, dataType = "string", paramType = "path")
    public JsonResult<String> validatePhoneNumber(@PathVariable String phoneNumber) {
        User user = userService.selectByPhone(phoneNumber);
        ValidatePhoneResp phoneResp = new ValidatePhoneResp();
        if (user == null) {
            phoneResp.setPlatform(Boolean.FALSE);
            return JsonResult.success("不是平台用户", "0");
        } else {
            if (user.getIsMaster() != null && user.getIsMaster() != 0) {
                UserMaster master = masterService.getUserMasterByUserId(user.getId());
                if (master!=null){
                    if (CONSTANTS_2.equals(master.getStatus())){
                        return JsonResult.success("账号被冻结","5");
                    }
                }
                if (user.getIsMaster() == 1) {
                    return JsonResult.success("认证中", "2");
                } else if (user.getIsMaster() == 2) {
                    return JsonResult.success("已认证", "3");
                }else if (user.getIsMaster()==3){
                    return JsonResult.success("申请被管理员驳回","4");
                }
            } else {
                phoneResp.setPlatform(true);
                return JsonResult.success("未认证为师傅", CONSTANTS_1);
            }
        }
        return JsonResult.success();
    }

    @ApiOperation(value = "师傅认证-发送短信验证码", notes = "发送短信验证码")
    @RequestMapping(value = "/sendSmsCode/{phoneNumber}", method = RequestMethod.POST)
    @ApiImplicitParam(name = "phoneNumber", value = "手机号码", required = true, dataType = "string", paramType = "path")
    public JsonResult<String> sendSmsCode(@PathVariable String phoneNumber) {
        //发送验证码
        if (smsSendService.sendLoginVerifyCode(phoneNumber)) {
            return JsonResult.success();
        } else {
            return JsonResult.failure(ErrorEnum.VERIFY_CODE_SEND_ERROR.getCode(),
                    ErrorEnum.VERIFY_CODE_SEND_ERROR.getMsg());
        }
    }

    @ApiOperation(value = "师傅认证-校验验证码是否正确", notes = "校验验证码是否正确")
    @PostMapping("/checkValidCode")
    @ApiImplicitParam(name = "validCodeReq", value = "CheckValidCodeReq实体", required = true, dataType = "CheckValidCodeReq")
    public JsonResult<String> checkValidCode(@Valid @RequestBody CheckValidCodeReq validCodeReq) {
        if (recordService.validVerifyCode(validCodeReq.getPhone(), validCodeReq.getVerifyCode())) {
            return JsonResult.success();
        } else {
            return JsonResult.failure(ErrorEnum.VERIFY_CODE_VALID_ERROR.getCode(),
                    ErrorEnum.VERIFY_CODE_VALID_ERROR.getMsg());
        }
    }


    @ApiOperation(value = "师傅认证-服务列表", notes = "师傅技能分类列表")
    @PostMapping(value = "/getMasterServiceType")
    public JsonResult<List<ServiceTypeResp>> getMasterServiceType() {
        Map<String, String> map = DictUtil.keyValueList("SERVICE_CLASS");
        List<ServiceTypeResp> serviceTypeResps = new ArrayList<>();
        if (MapUtils.isNotEmpty(map)) {
            for (String key : map.keySet()) {
                ServiceTypeResp serviceTypeResp = new ServiceTypeResp();
                serviceTypeResp.setKey(key);
                serviceTypeResp.setValue(map.get(key));
                serviceTypeResps.add(serviceTypeResp);
            }
        }
        return JsonResult.success(serviceTypeResps);
    }

    @ApiOperation(value = "师傅认证-师傅技能分类列表", notes = "师傅技能分类列表")
    @PostMapping(value = "/getMasterSkillList/{agentId}")
    public JsonResult<List<Dict>> getMasterSkillList(@PathVariable String agentId) {
//        String value = DictUtil.keyValue("SERVICE_CLASS", code);
        if (CONSTANTS_1.equals(agentId)) {
            return JsonResult.success();
        }
        List<Dict> dictMain = new ArrayList<>();
        List<AgentServ> agentServs = agentServService.queryServByAgentId(agentId);
        if (CollectionUtils.isNotEmpty(agentServs)){
            agentServs.forEach(item->{
                Dict dict = new Dict();
                dict.setValue(item.getServiceName());
                dict.setCode(item.getServiceClass()+":"+item.getServiceCode());
                dictMain.add(dict);
            });
        }
        return JsonResult.success(dictMain);
    }


    @ApiOperation(value = "师傅认证-修改骑手协议状态", notes = "修改骑手协议状态，{isRider:0不同意,1同意}")
    @PostMapping(value = "/updateRiderProtocol/{isRider}")
    @ApiImplicitParam(name = "isRider", value = "是否同意骑手协议", required = true, dataType = "String", paramType = "path")
    public JsonResult<Boolean> updateRiderProtocol(@PathVariable String isRider) {
        //添加师傅信息
        if (StringUtils.isEmpty(isRider)) {
            return JsonResult.failure(ErrorEnum.REQUEST_PARAM_EMPTY.getMsg());
        }
        User user = userService.getById(getUserId());
        user.setIsRider(Integer.parseInt(isRider));
        return JsonResult.success(userService.modifyById(user));
    }

    @ApiOperation(value = "师傅技能可修改-已选中技能列表", notes = "获取师傅已选中可修改技能列表")
    @GetMapping(value = "/getMasterSkillList")
    public JsonResult<List<ServiceTypeResp>> getMasterSkillList() {
        //获取分站上门分类
        UserMaster master = masterService.getUserMasterByUserId(getUserId());
        String agentId = master.getAgentId();
        //获取技能列表
        String skillType = master.getSkillType();
        List<Dict> dicts = new ArrayList<>();
        try {
            com.alibaba.fastjson.JSONObject skillObj = JSON.parseObject(skillType);
            if (skillObj!=null){
                for (String key:skillObj.keySet()){

                    if (CONSTANTS_1.equals(key)){
                        Dict dict = new Dict();
                        dict.setValue("跑腿");
                        dict.setCode(CONSTANTS_1);
                        dicts.add(dict);
                    }else{
                        String skillStr = skillObj.getString(key);
                        if (StringUtils.isNotEmpty(skillStr)){
                            String[] args = skillStr.split(",");
                            for (String arg : args) {
                                Dict dict = new Dict();
                                AgentServ serv=  agentServService.queryServByAgentIdAndCode(agentId,key,arg);
                                if (serv!=null){
                                    dict.setCode(key+":"+serv.getServiceCode());
                                    dict.setValue(serv.getServiceName());
                                    dicts.add(dict);
                                }
                            }
                        }
                    }
//                    dicts.add(dict);
                }
            }
        }catch (Exception ex){
            logger.error("获取师傅技能列表异常:{}",ex);
        }
        return JsonResult.success(dicts);
    }


    @ApiOperation(value = "师傅技能可修改-修改技能列表保存", notes = "师傅修改技能列表保存")
    @PostMapping(value = "/updateMasterSkill")
    public JsonResult<String> updateMasterSkill(@RequestBody UpdateSkillReq skillReq) {
        try {
            List<ServiceTypeReq> serviceTypeReqs = skillReq.getServiceType();
            if (CollectionUtils.isEmpty(serviceTypeReqs)){
                logger.error("传入对象为空:{}", JSON.toJSONString(skillReq));
                return JsonResult.failure("请求技能列表为空");
            }
            JSONObject jsonObject = comsobbleSkill(serviceTypeReqs);
            UserMaster master = masterService.getUserMasterByUserId(getUserId());
            if (jsonObject==null){
                logger.error("技能对象为空:{}",JSON.toJSONString(skillReq));
                return JsonResult.failure("技能列表解析为空:{}",JSON.toJSONString(skillReq));
            }
            String serviceType = master.getServiceType();
            if (!jsonObject.containsKey(CONSTANTS_1)){
                if (CONSTANTS_1.equals(serviceType)){
                    serviceType = "2";
                }
            }
            master.setServiceType(serviceType);
            master.setSkillType(JSON.toJSONString(jsonObject));
            if(masterService.saveOrUpdate(master,false)){
                return JsonResult.success();
            }
        }catch (Exception ex){
            logger.error("获取师傅技能列表异常:{}",ex);
        }
        return JsonResult.failure("师傅技能列表修改错误");
    }



    @ApiOperation(value = "师傅认证-查找骑手协议", notes = "查找骑手协议")
    @PostMapping("/getRiderAgreement")
    public JsonResult getRiderAgreement() {
        return JsonResult.success(contentService.queryContentInfo(ProtocolTypeEnum.MASTER_PROTOCOL));
    }

    @ApiOperation(value = "上传技能图片", notes = "上传技能图片")
    @PostMapping("/uploadSkillPic")
    @ApiImplicitParam(name = "file", value = "图片文件", required = true)
    public JsonResult uploadSkillPic(@RequestParam("file") MultipartFile file) {
        UploadImgResp pic = uploadService.uploadImg(file, getUserId());
        UserCertifacate certifacate = certifacateService.selectByUserId(getUserId());
        if (certifacate != null) {
            certifacate.setSkillPic(pic.getName());
            certifacateService.updateById(certifacate);
        } else {
            UserCertifacate c = new UserCertifacate();
            c.setSkillPic(pic.getName());
            c.setUserId(getUserId());
            certifacateService.save(certifacate);
        }
        return JsonResult.success();
    }


    @ApiOperation(value = "师傅认证-师傅信息提交", notes = "师傅信息提交,{phone:手机号码,verifyCode:短信验证码,servicType:key值1,3(跑腿，技能)，value:对应相应技能列表接口返回的code值,选跑腿，value为空串}必传字段")
    @PostMapping(value = "/authenMaster")
    @ApiImplicitParam(name = "masterReq", value = "AuthenMasterReq实体", required = true, dataType = "AuthenMasterReq")
    public JsonResult<String> authenMaster(@Valid @RequestBody AuthenMasterReq masterReq) {
        //添加师傅信息
        logger.info("师傅认证请求入参:{}",JSON.toJSONString(masterReq));
        User user = userService.getById(getUserId());
        if (StringUtils.isEmpty(user.getPhone())||!user.getPhone().equals(masterReq.getPhone())){
            return JsonResult.failure("当前登录用户手机与师傅验证手机不一致");
        }
        String masterName = masterReq.getName();
        if (StringUtils.isEmpty(masterName)){
            UserCertifacate certifacate = certifacateService.selectByUserId(user.getId());
            if (certifacate != null) {
                masterName = certifacate.getName();
            }
        }
        user.setSmsCode(masterReq.getVerifyCode());
        user.setSmsTime(new Date());
        user.setIsMaster(1);
        user.setMasterStatus(CONSTANTS_0);
        boolean flag = userService.modifyById(user);
        boolean masterFlag = false;
        if (flag) {
            //添加师傅分站绑定信息
            Date now = new Date();
            JSONObject jsonObject = new JSONObject();
            String serviceType = CONSTANTS_1;
            if (CollectionUtils.isNotEmpty(masterReq.getServiceType())&&masterReq.getServiceType().size()>1){
                serviceType = "2";
            }
            jsonObject = comsobbleSkill(masterReq.getServiceType());
            UserMaster userMaster = masterService.getUserMasterByUserId(getUserId());
            AdminScoreManagentment scoreManagentment = scoreManagentmentService.findOne();

            String masterScore = "10";
            if (scoreManagentment!=null){
                masterScore = scoreManagentment.getDefaultScore()==null?"10":String.valueOf(scoreManagentment.getDefaultScore());
            }
            if (userMaster == null) {
                userMaster  = new UserMaster();
                userMaster.setUserId(user.getId());
                userMaster.setMasterName(masterName);
                userMaster.setAuthStatus(CONSTANTS_0);
                userMaster.setLatitude(masterReq.getLatitude());
                userMaster.setStatus(CONSTANTS_1);
                userMaster.setScore(masterScore);
                userMaster.setTotalTimes(BigDecimal.ZERO);
                userMaster.setAgentId(masterReq.getAgentId());
                userMaster.setCreateDt(now);
                userMaster.setUpdateDt(now);
                userMaster.setServiceType(serviceType);
                userMaster.setMasterName(masterName);
                userMaster.setSkillType(JSONObject.toJSONString(jsonObject));
                userMaster.setLongitude(masterReq.getLongitude());
                userMaster.setMasterStars(scoreManagentmentService.parseStar(Long.parseLong(masterScore)));
                masterFlag = masterService.saveOrUpdate(userMaster,true);
            } else {
                userMaster.setUserId(user.getId());
                userMaster.setLatitude(masterReq.getLatitude());
                userMaster.setStatus(CONSTANTS_1);
                userMaster.setAuthStatus(CONSTANTS_0);
                userMaster.setAgentId(masterReq.getAgentId());
                userMaster.setCreateDt(now);
                userMaster.setUpdateDt(now);
                userMaster.setServiceType(serviceType);
                userMaster.setMasterName(masterName);
                userMaster.setSkillType(JSONObject.toJSONString(jsonObject));
                userMaster.setLongitude(masterReq.getLongitude());
                masterFlag = masterService.saveOrUpdate(userMaster,false);
            }
            if (masterFlag) {
                return JsonResult.success("师傅认证提交成功");
            }
        }
        return JsonResult.failure(ErrorEnum.MASTER_AUTHEN_COMIT_ERROR.getMsg());
    }

    private JSONObject comsobbleSkill(List<ServiceTypeReq> serviceType){
        JSONObject jsonObject = new JSONObject();
        if (CollectionUtils.isNotEmpty(serviceType)) {
            serviceType.forEach(item->{
                if (CONSTANTS_1.equals(item.getKey())) {
                    jsonObject.put(item.getKey(), item.getValue());
                } else {
                    String[] servictParent = item.getValue().split(",");
                    for (int i = 0; i < servictParent.length; i++) {
                        String child = servictParent[i];
                        String[] args = child.split(":");
                        if (jsonObject.containsKey(args[0])){
                            String skill = jsonObject.getString(args[0]);
                            skill +=","+args[1];
                            jsonObject.put(args[0],skill);
                        }else{
                            jsonObject.put(args[0],args[1]);
                        }
                    }
                }
            });
        }
        return jsonObject;
    }

    /************************************认证流程end********************************************/


    /************************************首页展示start********************************************/


    @ApiOperation(value = "更新师傅位置", notes = "更新师傅位置")
//    @PreAuthorize("hasRole('ROLE_MASTER')")
    @PostMapping(value = "/updateMasterPos")
    public JsonResult updateMasterPos(@Valid @RequestBody LocationReq locationReq) {
        UserMaster master = masterService.getUserMasterByUserId(getUserId());
        if (master!=null){
            if (StringUtils.isNotEmpty(locationReq.getLatitude())&&StringUtils.isNotEmpty(locationReq.getLongitude())){
                master.setLatitude(locationReq.getLatitude());
                master.setLongitude(locationReq.getLongitude());
                boolean flag = masterService.saveOrUpdate(master,false);
                if (flag) {
                    return JsonResult.success();
                } else {
                    return JsonResult.failure(ErrorEnum.UPDATE_LOCATION_ERROR.getMsg());
                }
            }
        }
        return JsonResult.success();
    }

    @ApiOperation(value = "师傅首页-更新师傅当前状态", notes = "更新师傅当前状态接口(接单，立即收工)")
    @GetMapping(value = "/updateMasterStatus")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParam(name = "masterStatus", value = "师傅状态", required = true, dataType = "String")
    public JsonResult updateMasterStatus(@RequestParam(value = "masterStatus", required = true)String masterStatus) {
        try {
            if (!"0,1".contains(masterStatus)){
                return JsonResult.failure(ErrorEnum.MASTER_STATUS_PARAM_ERROR.getMsg());
            }

            SysOpLog opLog = new SysOpLog();
            UserMaster master = masterService.getUserMasterByUserId(getUserId());
            if (!CONSTANTS_1.equals(masterStatus)){
                List<Integer> statusList = new ArrayList<>();
                statusList.add(Constant.OrderStatusEnum.SERVERING.getCode());
                statusList.add(Constant.OrderStatusEnum.FETCHING.getCode());
                statusList.add(Constant.OrderStatusEnum.SENDING.getCode());
                PageInfo<OrderNearResp> orders = orderService.findOrderByStatusPage(statusList, getUserId(), 1, 10);
                if (CollectionUtils.isNotEmpty(orders.getList())){
                    return JsonResult.failure("师傅尚有正在服务的订单");
                }
                Date now = new Date();
                master.setOfflineDate(now);
                BigDecimal timesed = new BigDecimal(0);
                String times = DateUtil.getDateMs(now,master.getOnlineDate()==null?new Date():master.getOnlineDate());
                if (master.getTotalTimes()!=null){
                    timesed = master.getTotalTimes();
                }
                master.setTotalTimes(timesed.add(new BigDecimal(times).setScale(2, BigDecimal.ROUND_HALF_UP)).setScale(2,BigDecimal.ROUND_HALF_UP));
                if (!saveOplog(getUserId(),"下线")){
                    logger.error("下线存入日志表异常:{}",getUserId());
                }
            }else{
                if (validateMarign(master.getAgentId(),getUserId())){
                    return JsonResult.failure("师傅保证金不足");
                }
                master.setOnlineDate(new Date());
                if (!saveOplog(getUserId(),"上线")){
                    logger.error("上线存入日志表异常:{}",getUserId());
                }
            }
            User user = userService.getById(getUserId());
            user.setMasterStatus(masterStatus);
            if (userService.modifyById(user)){
                 masterService.saveOrUpdate(master,false);
                return  JsonResult.success();
            }else{
                return JsonResult.failure(ErrorEnum.UPDATE_STATUS_ERROR.getMsg());
            }
        }catch (Exception ex){
            logger.error("更改在线状态异常:{}",ex);
        }
        return JsonResult.success();
    }

    private boolean saveOplog(Long userId,String onlineStatus){
        Date now  = new Date();
        SysOpLog sysOpLog = new SysOpLog();
        sysOpLog.setCreatedTime(now);
        sysOpLog.setUpdateTime(now);
        sysOpLog.setRemark(onlineStatus);
        sysOpLog.setType(CONSTANTS_0);
        sysOpLog.setUserId(userId);
        return opLogService.saveOrUpdate(sysOpLog,true);
    }


    @ApiOperation(value = "师傅首页-每周优秀骑手", notes = "每周优秀骑手")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @PostMapping(value = "/goodRiderList")
    public JsonResult<MasterScoreLevel> goodRiderList() {
        List<MasterScoreLevel> masterScoreDetails = detailsService.getMasterLevelList();
        if (CollectionUtils.isNotEmpty(masterScoreDetails)){
            UserMaster user = masterService.getUserMasterByUserId(getUserId());
            for (int i = 0; i < masterScoreDetails.size(); i++) {
                MasterScoreLevel level = masterScoreDetails.get(i);
                level.setHeadPic(StringUtils.isNotEmpty(level.getHeadPic())?uploadService.getPicUrlPath(level.getHeadPic()):pic);
                level.setCurrentName(user.getMasterName());
                level.setRank(i+1);
                level.setUserId(String.valueOf(getUserId()));
                if (StringUtils.isNotEmpty(user.getMasterName())
                        &&user.getMasterName().equals(level.getMasterName())){
                    level.setMyRank(level.getRank());
                }
            }
        }
        return JsonResult.success(masterScoreDetails);
    }


    @ApiOperation(value = "师傅首页-我的综合评分", notes = "我的综合评分")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @PostMapping(value = "/myOverallScore")
    public JsonResult<MasterScoreResp> myOverallScore() {
        UserMaster master = masterService.getUserMasterByUserId(getUserId());
        MasterScoreResp scoreResp = new MasterScoreResp();
        if (master == null) {
            scoreResp.setScore(CONSTANTS_0);
            return JsonResult.success(scoreResp);
        }
        scoreResp.setScore(master.getScore());
        return JsonResult.success(scoreResp);
    }

    @ApiOperation(value = "师傅首页-我的综合评分(明细)", notes = "我的综合评分")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @PostMapping(value = "/myOverallScoreDetails")
    public JsonResult<MasterScoreDetailsResp> myOverallScoreDetails(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM + "") int pageNum,
                                                                    @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE + "") int pageSize) {
        PageInfo<MasterScoreDetailsResp> resp = detailsService.getMasterScoreDetails(getUserId(), pageNum, pageSize);
        return JsonResult.success(resp);
    }

    @ApiOperation(value = "师傅首页-订单接口加拒绝", notes = "指定师傅接单接口")
    @PostMapping(value = "/acceptOrderByMaster")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "string"),
            @ApiImplicitParam(name = "acceptFlag", value = "接单标识0：拒绝接单,1：同意", required = true, dataType = "string")
    })    public JsonResult acceptOrderByMaster(@RequestParam(value = "orderNo", required = true) String orderNo,
                                          @RequestParam(value = "acceptFlag", required = true) String acceptFlag) {
        //获取师傅最大接单笔数
        QueryWrapper<SysParam> query = new QueryWrapper<>();
        query.eq("name","MASTER_ORDER_LIMIT");
        SysParam param = sysParamService.getOne(query);
        if (param !=null&&StringUtils.isNotEmpty(param.getValue())&&StringUtils.equals(CONSTANTS_1,acceptFlag)){
            List<Integer> statusList = new ArrayList<>();
            statusList.add(Constant.OrderStatusEnum.SERVERING.getCode());
            statusList.add(Constant.OrderStatusEnum.FETCHING.getCode());
            statusList.add(Constant.OrderStatusEnum.SENDING.getCode());
            List<OrderNear> orders = orderService.getOrderByStatusList(getUserId(), statusList);
            if (CollectionUtils.isNotEmpty(orders) && orders.size() >= Integer.parseInt(param.getValue())) {
                return JsonResult.failure("师傅最多同时接"+param.getValue()+"单!");
            }
        }

        Order order = orderService.findOrderByOrderNo(orderNo);
        if (order == null) {
            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getMsg());
        }
        Long master_id = order.getMasterId();
        if (master_id!=null){
            if (!StringUtils.equals(master_id.toString(),getUserId().toString())){
                return JsonResult.success(RECIVED_FAIL);
            }
        }
        User user = userService.getById(getUserId());
        if (user==null){
            logger.error("-订单接口加拒绝用户Id：{}",getUserId());
            return JsonResult.failure("当前用户不存在");
        }
        if (!StringUtils.equals(CONSTANTS_1,acceptFlag)){
            logger.info("调用拒绝接口开始:{}",order.getOrderNo());
            order.setMasterId(null);
            order.setStatus(Constant.OrderStatusEnum.WAIT_ACCEPT.getCode());
            order.setDispatchMaster(null);
            if (orderService.updateOrderById(order)){
                logger.info("调用拒绝接口结束更新订单表,开始更新派工单表:{}",order.getOrderNo());
                updateDispatch(order.getId(),false);
                return JsonResult.success();
            }
        }

        if (!CONSTANTS_1.equals(acceptFlag)){
            return JsonResult.failure("接单标识参数不能识别");
        }
        //订单状态为服务中
        //根据订单类型对应的角色是跑腿师傅还是技术维修师傅
        int status = Constant.OrderStatusEnum.FETCHING.getCode();
        if (order.getType() != 1) {
            status = Constant.OrderStatusEnum.SERVERING.getCode();
        }
        UserMaster master = masterService.getUserMasterByUserId(getUserId());
        //生成服务确认吗
        //order.setVerifyCode("6666");//测试使用
        order.setVerifyCode(StringUtil.generateRandom(4));
        order.setStatus(status);
        order.setMasterId(getUserId());
        boolean flag = orderService.updateOrderById(order);
        if (flag) {
            MasterOrderAccitity orderAccitity = new MasterOrderAccitity();
            orderAccitity.setAcctityStatus(MasterConstants.MasterAcctityStatus.ACCTITY_STATUS_1.getCode());
            orderAccitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_1.getCode());
            orderAccitity.setStatus(CONSTANTS_1);
            orderAccitity.setCreateDt(new Date());
            orderAccitity.setUpdateDt(new Date());
            orderAccitity.setOrderId(order.getId());
            orderAccitity.setOrderNo(order.getOrderNo());
            orderAccitity.setMasterId(getUserId());
            if (accitityService.saveAcctity(orderAccitity)){
                updateDispatch(order.getId(),true);
                String append = getOrderTypeAppend(order.getAgentId(),order.getType(),order.getChildType(),String.valueOf(order.getHasPartner()==null?0:order.getHasPartner())) + ","+master.getMasterName().substring(0,1);
                parsePushData(order,"师傅已接单","订单状态通知","【阿四服务】" + append+"师傅已接单！");
                return JsonResult.success();
            }
            return JsonResult.failure(ErrorEnum.ORDER_RECIVED_ERROR.getMsg());
        }
        return JsonResult.failure(ErrorEnum.ORDER_RECIVED_ERROR.getMsg());
    }

    /**
     *
     * 判断保证金
     * @param agentId
     * @param
     * @return
     */
    private Boolean validateMarign(String agentId,Long userId){
        User user = userService.getById(userId);
        BigDecimal accountBalance = BigDecimal.ZERO;
        if (user!=null){
            accountBalance = user.getAccountBalance();
        }
        List<SysAgent> agent = agentService.getInfoByAgentId(agentId);
        BigDecimal margin = new BigDecimal(0);
        if(CollectionUtils.isNotEmpty(agent)){
            SysAgent sysAgent = agent.get(0);
            margin = sysAgent.getMargin();
        }
        BigDecimal userBalance = accountBalance==null?BigDecimal.ZERO:accountBalance;
        if (userBalance.compareTo(margin)==-1){
            return  Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    private String getOrderTypeAppend(String agentId,Integer type,Integer childType,String hasPartener){
        StringBuffer typeAppend = new StringBuffer("订单-");
//        typeAppend.append("订单").append("-");
        if (Constant.OrderTypeEnum.PAO_TUI.getCode().toString().equals(String.valueOf(type))){
            typeAppend.append(Constant.OrderTypeEnum.PAO_TUI.getMessage()).append("-");
            if (StringUtils.equals("1",hasPartener)){
                typeAppend.append("合作商家");
            }else{
                switch (childType){
                    case 11:
                        typeAppend.append("帮我送");
                        break;
                    case 12:
                        typeAppend.append("帮我取");
                        break;
                    case 13:
                        typeAppend.append("随意购");
                        break;
                    case 14:
                        typeAppend.append("外卖");
                    default:
                        typeAppend.append("未知");
                        break;

                }
            }
        }else{
            Dict dict = dictService.getDictByNameAndCode("SERVICE_CLASS",String.valueOf(type));
            AgentServ serv = agentServService.queryServByAgentIdAndCode(agentId,String.valueOf(type),String.valueOf(childType));
            if (dict==null&&serv!=null){
                typeAppend.append("万能帮办").append("-").append(serv.getServiceName());
            }else if (dict==null&&serv==null){
                typeAppend.append("万能帮办").append("-").append("未知");
            }else if (dict!=null&&serv!=null){
                typeAppend.append(dict.getValue()).append("-").append(serv.getServiceName());
            }else{
                typeAppend.append("万能帮办").append("-").append("未知");
            }
        }
        return typeAppend.toString();

    }




    @ApiOperation(value = "师傅首页-接单", notes = "接单接口,参数{orderNo}必传")
    @PostMapping(value = "/acceptOrder/{orderNo}")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "String", paramType = "path")
    public JsonResult orderPromising(@PathVariable String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        User user = userService.getById(getUserId());
        if (StringUtils.isEmpty(user.getMasterStatus())||CONSTANTS_0.equals(user.getMasterStatus())){
            return JsonResult.failure(ErrorEnum.MASTER_STATUS_NOT_IN.getMsg());
        }
        Order order = orderService.findOrderByOrderNo(orderNo);
        if (order == null) {
            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getMsg());
        }
        Long master_id = order.getMasterId();
        if (master_id!=null){
            if (!StringUtils.equals(master_id.toString(),getUserId().toString())){
                return JsonResult.success(RECIVED_FAIL);
            }
        }
        //获取师傅最大接单笔数
        QueryWrapper<SysParam> query = new QueryWrapper<>();
        query.eq("name","MASTER_ORDER_LIMIT");
        SysParam param = sysParamService.getOne(query);
        if (param !=null&&StringUtils.isNotEmpty(param.getValue())){
            List<Integer> statusList = new ArrayList<>();
            statusList.add(Constant.OrderStatusEnum.FETCHING.getCode());
            statusList.add(Constant.OrderStatusEnum.SERVERING.getCode());
            statusList.add(Constant.OrderStatusEnum.SENDING.getCode());
            List<OrderNear> orders = orderService.getOrderByStatusList(getUserId(), statusList);
            if (CollectionUtils.isNotEmpty(orders) && orders.size() >= Integer.parseInt(param.getValue())) {
                return JsonResult.failure("师傅最多同时接"+param.getValue()+"单!");
            }
        }
        //订单状态为服务中
        //根据订单类型对应的角色是跑腿师傅还是技术维修师傅
        int status = Constant.OrderStatusEnum.FETCHING.getCode();
        if (order.getType() != 1) {
            status = Constant.OrderStatusEnum.SERVERING.getCode();
        }
        //生成服务确认吗
        //order.setVerifyCode("6666");//测试使用
        order.setVerifyCode(StringUtil.generateRandom(4));
        order.setStatus(status);
        order.setMasterId(getUserId());
        boolean flag = orderService.updateOrderById(order);
        if (flag) {
            Date now = new Date();
            MasterOrderAccitity orderAccitity = new MasterOrderAccitity();
            orderAccitity.setStatus(CONSTANTS_1);
            orderAccitity.setAcctityStatus(MasterConstants.MasterAcctityStatus.ACCTITY_STATUS_1.getCode());
            orderAccitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_1.getCode());
            orderAccitity.setCreateDt(now);
            orderAccitity.setUpdateDt(now);
            orderAccitity.setOrderNo(order.getOrderNo());
            orderAccitity.setOrderId(order.getId());
            orderAccitity.setMasterId(getUserId());
            UserMaster master = masterService.getUserMasterByUserId(getUserId());
            if (accitityService.saveAcctity(orderAccitity)){
                updateDispatch(order.getId(),true);
                String  append = getOrderTypeAppend(order.getAgentId(),order.getType(),order.getChildType(),String.valueOf(order.getHasPartner()==null?0:order.getHasPartner())) + ","+master.getMasterName().substring(0,1);
                parsePushData(order,"师傅已接单","订单状态通知","【阿四服务】 " + append+"师傅已接单！");
                return JsonResult.success();
            }
            return JsonResult.failure(ErrorEnum.ORDER_RECIVED_ERROR.getMsg());
        }
        return JsonResult.failure(ErrorEnum.ORDER_RECIVED_ERROR.getMsg());
    }


    @ApiOperation(value = "师傅首页-附近订单", notes = "附近订单")
    @PostMapping(value = "/getNearOrderList")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParam(name = "nearOrderReq", value = "NearOrderReq实体", required = true, dataType = "NearOrderReq")
    public JsonResult<OrderNearResp> getNearOrderList(@Valid @RequestBody NearOrderReq nearOrderReq) {


        if (nearOrderReq.getDistanceLimit() == null || nearOrderReq.getDistanceLimit() == 0) {
            nearOrderReq.setDistanceLimit(MasterConstants.KILO_METRE);
        }else{
            nearOrderReq.setDistanceLimit(nearOrderReq.getDistanceLimit());
        }
        Map<String, String> servcieMap = masterService.getMasterServiceType(getUserId());
        UserMaster master = masterService.getUserMasterByUserId(getUserId());
        List<OrderNearResp> nearResps = new ArrayList<>();

        //查询是否自动派单，如果是不返回数据
        SysAgent agent = agentService.getById( master.getAgentId());
        if (master !=null && !"auto".equals(agent.getDispatchType())){
            nearResps = orderService.findNearOrderList(nearOrderReq, master.getAgentId(), servcieMap,getUserId());
            if (CollectionUtils.isNotEmpty(nearResps)){
                nearResps.forEach(item->{
                    item.setExpectedIncome(String.valueOf(getIncome(item.getOrderNo()).doubleValue()));
                    if(item.getImages() != null){
                        //处理图片
                        List<String> images = new ArrayList<String>();
                        Arrays.stream(Optional.ofNullable(item.getImages()).get().split(",")).forEach(o->{
                            images.add(componentUtil.convertImgUrl(o));
                        });
                        item.setImagesList(images);
                    }
                    if(item.getGoodsImages() != null){
                        //处理图片
                        List<String> images = new ArrayList<String>();
                        Arrays.stream(Optional.ofNullable(item.getGoodsImages()).get().split(",")).forEach(o->{
                            images.add(componentUtil.convertImgUrl(o));
                        });
                        item.setGoodsImagesList(images);
                    }
                    //处理音频
                    Optional.ofNullable(item.getAudio()).ifPresent(o->item.setAudio(componentUtil.convertImgUrl(o)));

                });
            }
        }
        return JsonResult.success(nearResps);
    }


    @ApiOperation(value = "师傅首页-已接订单", notes = "已接订单")
    @PostMapping(value = "/receivedOrders")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    public JsonResult<OrderNearResp> receivedOrders(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM + "") int pageNum,
                                                    @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE + "") int pageSize) {
        List<Integer> statusList = new ArrayList<>();
        statusList.add(Constant.OrderStatusEnum.SERVERING.getCode());
        statusList.add(Constant.OrderStatusEnum.FETCHING.getCode());
        statusList.add(Constant.OrderStatusEnum.SENDING.getCode());
        PageInfo<OrderNearResp> orders = orderService.findOrderByStatusPage(statusList, getUserId(), pageNum, pageSize);
        if (CollectionUtils.isNotEmpty(orders.getList())){
            List<OrderNearResp> nearResps = orders.getList();
            nearResps.forEach(item->{
                if(item.getImages() != null){
                    //处理图片
                    List<String> images = new ArrayList<String>();
                    Arrays.stream(Optional.ofNullable(item.getImages()).get().split(",")).forEach(o->{
                        images.add(componentUtil.convertImgUrl(o));
                    });
                    item.setImagesList(images);
                }
                item.setExpectedIncome(String.valueOf(getIncome(item.getOrderNo())));
                if(item.getGoodsImages() != null){
                    //处理图片
                    List<String> images = new ArrayList<String>();
                    Arrays.stream(Optional.ofNullable(item.getGoodsImages()).get().split(",")).forEach(o->{
                        images.add(componentUtil.convertImgUrl(o));
                    });
                    item.setGoodsImagesList(images);
                }
                //处理音频
                Optional.ofNullable(item.getAudio()).ifPresent(o->item.setAudio(componentUtil.convertImgUrl(o)));
            });
        }
        return JsonResult.success(orders);
    }

    @ApiOperation(value = "师傅首页-转回订单池", notes = "转回订单池")
    @PostMapping(value = "/restitutioOrder")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    public JsonResult<OrderNearResp> receivedOrders(@RequestParam(value = "orderNo", required = true) String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        Order order = orderService.findOrderByOrderNo(orderNo);
        if (order == null) {
            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getMsg());
        }
        order.setCancleTime(new Date());
        order.setStatus(Constant.OrderStatusEnum.WAIT_ACCEPT.getCode());
        if (orderService.updateOrderById(order)) {
            updateDispatch(order.getId(),false);
            return JsonResult.success(accitityService.updateOrderAccitity(order.getId(), CONSTANTS_0));
        }
        return JsonResult.failure(ErrorEnum.SYSTEM_ERROR.getMsg());
    }


    @ApiOperation(value = "师傅首页-已完成订单", notes = "已完成订单")
    @PostMapping(value = "/completeOrder")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    public JsonResult<OrderNearResp> completeOrder(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM + "") int pageNum,
                                                   @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE + "") int pageSize) {
        List<Integer> statusList = new ArrayList<>();
        statusList.add(Constant.OrderStatusEnum.OK.getCode());
        statusList.add(Constant.OrderStatusEnum.WAIT_ACCEPT.getCode());
        PageInfo<OrderNearResp> orders = orderService.findOrderByStatusPage(statusList, getUserId(), pageNum, pageSize);
        if (CollectionUtils.isNotEmpty(orders.getList())){
            List<OrderNearResp> nearResps = orders.getList();
            nearResps.forEach(item->{
                if(item.getImages() != null){
                    //处理图片
                    List<String> images = new ArrayList<String>();
                    Arrays.stream(Optional.ofNullable(item.getImages()).get().split(",")).forEach(o->{
                        images.add(componentUtil.convertImgUrl(o));
                    });
                    item.setImagesList(images);
                }
                if(item.getGoodsImages() != null){
                    //处理图片
                    List<String> images = new ArrayList<String>();
                    Arrays.stream(Optional.ofNullable(item.getGoodsImages()).get().split(",")).forEach(o->{
                        images.add(componentUtil.convertImgUrl(o));
                    });
                    item.setGoodsImagesList(images);
                }
                //处理音频
                Optional.ofNullable(item.getAudio()).ifPresent(o->item.setAudio(componentUtil.convertImgUrl(o)));

            });
        }
        return JsonResult.success(orders);
    }

    @ApiOperation(value = "订单详情", notes = "订单详情,参数{orderNo}必传")
    @PostMapping(value = "/completeOrder/{orderNo}")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "String", paramType = "path")
    public JsonResult<OrderNearResp> completeOrder(@PathVariable String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        UserMaster master = masterService.getUserMasterByUserId(getUserId());

        List<OrderNearResp> orders = orderService.getOrderByStatus(null, null, orderNo);

        if (CollectionUtils.isNotEmpty(orders)){
            orders.forEach(item->{
                item.setExpectedIncome(String.valueOf(getIncome(orderNo).doubleValue()));
                if(item.getImages() != null){
                    //处理图片
                    List<String> images = new ArrayList<String>();
                    Arrays.stream(Optional.ofNullable(item.getImages()).get().split(",")).forEach(o->{
                        images.add(componentUtil.convertImgUrl(o));
                    });
                    item.setImagesList(images);
                }
                if(item.getGoodsImages() != null){
                    //处理图片
                    List<String> images = new ArrayList<String>();
                    Arrays.stream(Optional.ofNullable(item.getGoodsImages()).get().split(",")).forEach(o->{
                        images.add(componentUtil.convertImgUrl(o));
                    });
                    item.setGoodsImagesList(images);
                }
                //处理音频
                Optional.ofNullable(item.getAudio()).ifPresent(o->item.setAudio(componentUtil.convertImgUrl(o)));

            });
        }
        return JsonResult.success(orders);
    }


    @ApiOperation(value = "师傅首页-title信息", notes = "师傅首页title信息")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @PostMapping(value = "/masterTitleMessage")
    public JsonResult<MasterTitleMessageResp> masterTitleMessage() {
//        List<OrderNearResp> orders = orderService.getOrderByStatus(getUserId(),null,orderNo);
        Long userId = getUserId();
        MasterTitleMessageResp titleMessageResp = new MasterTitleMessageResp();
        //用户信息
//        UserCertifacate user = certifacateService.selectByUserId(userId);
        UserMaster master = masterService.getUserMasterByUserId(userId);
        User users = userService.getById(getUserId());
        Date onlineDate =  master.getOnlineDate();
        if (users != null) {
            titleMessageResp.setMasterName(master.getMasterName());
            Invite invite = inviteService.queryLastInvite();
            if (invite!=null){
                titleMessageResp.setInviteUrl(invite.getUrl()+getUserId());
            }
            titleMessageResp.setAccountStatus(master.getStatus());
            titleMessageResp.setHeadPic(StringUtils.isNotEmpty(users.getAvatarUrl())?uploadService.getPicUrlPath(users.getAvatarUrl()):"");
            titleMessageResp.setMasterStatus(StringUtils.isNotEmpty(users.getMasterStatus())?users.getMasterStatus():CONSTANTS_0);
            if (CONSTANTS_1.equals(users.getMasterStatus())){
                String date  = DateUtil.dateToString(master.getOnlineDate(),"yyyy-MM-dd");
                String nowStr = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
                if (date.equals(nowStr)){
                    String ms = DateUtil.getDateMs(new Date(),onlineDate==null?new Date():onlineDate);
                    String timesDTy = opLogService.countTimes(consebble(getUserId()));
                    logger.info("用户当日在线时间计算:{}",timesDTy);
                    if (CONSTANTS_0.equals(timesDTy)){
                        titleMessageResp.setOnlineTimes(String.valueOf((Double.parseDouble(ms))));
                    }else{
                        titleMessageResp.setOnlineTimes(String.valueOf((Double.parseDouble(ms))+Double.parseDouble(timesDTy)*60));
                    }
                    titleMessageResp.setOnlineTimes(String.valueOf(Double.parseDouble(ms)));
                }else if (date.compareTo(nowStr)<0){
                    String ms = DateUtil.getDateMs(new Date(),DateUtil.stringtoDate(nowStr+" 00:00:00","yyyy-MM-dd HH:mm:ss"));
                    titleMessageResp.setOnlineTimes(String.valueOf(Double.parseDouble(ms)));
                }
            }else{
                titleMessageResp.setOnlineTimes(CONSTANTS_0);
            }
        }
        //今日完成訂数
        getMasterTitileDetails(master, titleMessageResp);
        return JsonResult.success(titleMessageResp);
    }

    private SysOpLog consebble(Long userId){
        SysOpLog opLog = new SysOpLog();
        opLog.setType(CONSTANTS_0);
        opLog.setCreatedTime(new Date());
        opLog.setUserId(userId);
        return opLog;
    }


    @ApiOperation(value = "师傅首页-我的钱包信息账户余额", notes = "我的钱包信息账户余额:返回accountBalance余额")
    @PostMapping(value = "/masterPocket")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    public JsonResult masterPocket() {
        Long userId = getUserId();
//        //用户信息
        User user = userService.getById(userId);
        return JsonResult.success(String.valueOf(user.getAccountBalance()));
    }


    /************************************首页展示end********************************************/

    /************************************订单服务流程start********************************************/


//    @ApiOperation(value = "订单服务流程-万能帮办指定师傅下单", notes = "万能帮办指定师傅下单")
//    @PostMapping(value = "/inReciveAddress")
//    @PreAuthorize("hasRole('ROLE_MASTER')")
//    @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "String")
//    public JsonResult inReciveAddress(@RequestParam("orderNo") String orderNo) {
//        if (StringUtils.isEmpty(orderNo)) {
//            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getMsg());
//        }
//        Order order = orderService.findOrderByOrderNo(orderNo);
//        if (order == null) {
//            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getCode(), ErrorEnum.ORDER_NOT_EXIST.getMsg());
//        }
//        MasterOrderAccitity accitity = accitityService.getMasterAccitityByOrderId(order.getId(), null);
//        accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_3.getCode());
//        accitityService.updateAcctityById(accitity);
//        return JsonResult.success();
//    }


    @ApiOperation(value = "订单服务流程-订单进程查询", notes = "订单进程接口,参数{orderNo}必传,返回成功code:1失败-1")
    @PostMapping(value = "/getOrderProgress/{orderNo}")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "String", paramType = "path")
    public JsonResult<MasterAccitityData> getOrderProgress(@PathVariable String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        Order order = orderService.findOrderByOrderNo(orderNo);

        UserMaster master = masterService.getUserMasterByUserId(getUserId());
        if (order != null) {
            Date taskTime = order.getTaskTime();
            MasterAccitityData accitityData = accitityService.getMasterAccitityData(order.getId(), orderNo);
            if ("2".equals(accitityData.getPriceWay())){
                if (accitityData.getStartTime()==null){
                    accitityData.setServerTimes(CONSTANTS_0);
                }else{
                    Date endTime = accitityData.getEndTime()==null?new Date():accitityData.getEndTime();
                    Date startDate = accitityData.getStartTime();
                    String serverTimes = String.valueOf(new BigDecimal(String.valueOf((endTime.getTime()-startDate.getTime())/1000)).setScale(1,BigDecimal.ROUND_HALF_DOWN));
                    accitityData.setServerTimes(serverTimes);
                }
            }else{
                accitityData.setServerTimes(CONSTANTS_0);
            }
            accitityData.setTaskTime(time(orderNo,CONSTANTS_1,master,order.getTaskTime()));
            if (MasterConstants.MasterOrderCurrentStatus.STATUS_5.getCode().
                    equals(accitityData.getAcctityStatus())&&
                    (!"1,2,3,4".contains(accitityData.getAcctityStatus()))){
                accitityData.setTaskTime(time(orderNo,"2",master,order.getTaskTime()));
            }
//            accitityData.setTaskTime(String.valueOf(15*60));
            return JsonResult.success(accitityData);
        } else {
            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getMsg());
        }
    }


    @ApiOperation(value = "订单服务流程-发货人(技术服务类型下单人)手机号码", notes = "发货人手机号码接口,参数{orderNo}必传,返回成功code:1失败-1,acceptFlag 1为确认，0为获取手机号")
    @PostMapping(value = "/getShipperPhone/{orderNo}")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "String", paramType = "path")
    public JsonResult getShipperPhone(@PathVariable String orderNo, @RequestParam(value = "acceptFlag", required = false) String acceptFlag) {
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        Order order = orderService.findOrderByOrderNo(orderNo);
        if (order == null) {
            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getCode(), ErrorEnum.ORDER_NOT_EXIST.getMsg());
        }
        Address address = null;
        String phone = StringUtils.EMPTY;
        if (order.getHasPartner()==1){
            User user = userService.getById(order.getUserId());
            phone = user.getPartnerPhone();
        }else{
            if(order.getType()== Constant.OrderTypeEnum.PAO_TUI.getCode()&&order.getChildType()==13){
                address = addressService.getById(order.getToAddressId());
            }else{
                address = addressService.getById(order.getFromAddressId()==null?order.getToAddressId():order.getFromAddressId());
            }
            phone = address.getPhone();
        }
        if (StringUtils.isNotEmpty(phone)) {
            //更新
            MasterOrderAccitity accitity = accitityService.getMasterAccitityByOrderId(order.getId(), null);
            if (StringUtils.equals("1",acceptFlag)&&validateAccitity(accitity.getCurrentStatus(), MasterConstants.MasterOrderCurrentStatus.STATUS_2.getCode())){
                accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_2.getCode());
                accitityService.updateAcctityById(accitity);
            }
            return JsonResult.success(phone);
        } else {
            logger.info("师傅订单【获取发货人手机】为空");
            return JsonResult.failure(ErrorEnum.USER_PHONE_NOT_FOUND.getCode(), ErrorEnum.USER_PHONE_NOT_FOUND.getMsg());
        }
    }


    @ApiOperation(value = "订单服务流程-已到达取货地(技术服务类型服务地已到达)", notes = "已到达取货地接口")
    @PostMapping(value = "/inReciveAddress")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "String")
    public JsonResult inReciveAddress(@RequestParam("orderNo") String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        Order order = orderService.findOrderByOrderNo(orderNo);
        if (order == null) {
            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getCode(), ErrorEnum.ORDER_NOT_EXIST.getMsg());
        }
        order.setOriginTime(new Date());
        order.setOperatorOrigin(0);
        MasterOrderAccitity accitity = accitityService.getMasterAccitityByOrderId(order.getId(), null);
        if (validateAccitity(accitity.getCurrentStatus(),MasterConstants.MasterOrderCurrentStatus.STATUS_3.getCode())){
            accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_3.getCode());
            if (accitityService.updateAcctityById(accitity)){
                orderService.updateOrderById(order);
            }
            if(order.getType() != Constant.OrderTypeEnum.PAO_TUI.getCode()){
                //发送短信，推送消息
                JsonResult smsResult = sendTakeDelivery("",order.getOrderNo());
                if(!JsonResult.CODE_SUCCESS.equals(smsResult.getCode())) return smsResult;
                String verifyCode = order.getVerifyCode();
                sysMessageService.saveMessage("服务确认码", "您的本次服务的确认码为【"+verifyCode+"】！", true, order.getUserId());
            }
        }
        return JsonResult.success();
    }


    @ApiOperation(value = "订单服务流程-强制到达目的地", notes = "强制到达目的地接口,参数{orderNo}必传")
    @PostMapping(value = "/froceArrival")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParam(name = "forceArrivedReq", value = "forceArrivedReq实体", required = true, dataType = "ForceArrivedReq")
    public JsonResult<LocationResp> froceArrival(@Valid @RequestBody ForceArrivedReq forceArrivedReq) {
        User user = userService.getById(getUserId());
        try {
            LocationResp locationResp = new LocationResp();
            Order near = orderService.findOrderByOrderNo(forceArrivedReq.getOrderNo());
            Date now  = new Date();
            if (near != null) {
                MasterOrderAccitity accitity = accitityService.getMasterAccitityByOrderId(near.getId(), null);
                String accCurStatusOld = accitity.getCurrentStatus();
                if (CONSTANTS_1.equals(forceArrivedReq.getArrivedFlag())) {
                    near.setOperatorOrigin(1);
                    near.setOriginTime(now);
                    if (near.getHasPartner()!=null&&near.getHasPartner()==1){
                        User parUser = userService.getById(near.getUserId());
                        locationResp.setLongitude(parUser.getPartnerLongitude());
                        locationResp.setLatitude(parUser.getPartnerLatitude());
                    }else{
                        Address address = addressService.getById(near.getToAddressId());
                        locationResp.setLongitude(address.getLongitude());
                        locationResp.setLatitude(address.getLatitude());

                    }
                    accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_3.getCode());
                } else {
                    near.setOperatorFinal(1);
                    near.setFinalTime(now);
                    if (near.getHasPartner()!=null&&near.getHasPartner()==1){
                        User parUser = userService.getById(near.getUserId());
                        locationResp.setLongitude(parUser.getPartnerLongitude());
                        locationResp.setLatitude(parUser.getPartnerLatitude());
                    }else{
                        Address address = addressService.getById(near.getToAddressId());
                        locationResp.setLatitude(address.getLatitude());
                        locationResp.setLongitude(address.getLongitude());
                    }
                    if (near.getType() == 1) {
                        switch (near.getChildType()) {
                            case 11:
                                if(near.getHasPartner()!=null&&near.getHasPartner()==1){
                                    accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_8.getCode());
                                    accitity.setAcctityStatus(MasterConstants.MasterAcctityStatus.ACCTITY_STATUS_3.getCode());
                                }else{
                                    if (near.getCollectionAmount()!=null&&near.getCollectionAmount().compareTo(BigDecimal.ZERO)==1){
                                        accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_6.getCode());
                                    }else{
                                        accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_7.getCode());
                                    }
                                    break;
                                }
                            case 12:
                            case 13:
                                accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_7.getCode());
                                break;
                            default:
                                break;
                        }
                    }else{
                        accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_3.getCode());
                    }
                }
                //更新
                if (validateAccitity(accCurStatusOld,accitity.getCurrentStatus())){
                    boolean flag = accitityService.updateAcctityById(accitity);
                    //合作商家订单完成
                    if (near.getHasPartner()!=null&&near.getHasPartner()==1&&flag&&!CONSTANTS_1.equals(forceArrivedReq.getArrivedFlag())){
                        near.setFinishStatus(1);
                        successOperate(near,"");
                    }else if (flag){
                        orderService.updateOrderById(near);
                        if(near.getType() !=1 ){
                            //发送短信，推送消息
                            JsonResult smsResult = sendTakeDelivery("",forceArrivedReq.getOrderNo());
                            if(!JsonResult.CODE_SUCCESS.equals(smsResult.getCode())) return smsResult;
                            String verifyCode = near.getVerifyCode();
                            sysMessageService.saveMessage("服务确认码", "您本次服务的确认码为【"+verifyCode+"】！", true, near.getUserId());
                        }
                    }else{
                        logger.error("订单进程表更新异常:{}",near.getOrderNo());
                    }
                }
            }
            return JsonResult.success(locationResp);
        } catch (Exception ex) {
            return JsonResult.failure(ErrorEnum.MASTER_FORCE_ERROR.getCode(), ErrorEnum.MASTER_FORCE_ERROR.getMsg());
        }
    }


    @ApiOperation(value = "订单服务流程-收货人手机号码", notes = "收货人手机号码接口,参数{orderNo}必传，acceptFlag 1为确认，0为获取手机号码")
    @PostMapping(value = "/getConsigneePhone/{orderNo}")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "String", paramType = "path")
    public JsonResult getConsigneePhone(@PathVariable String orderNo, @RequestParam(value = "acceptFlag", required = false) String acceptFlag) {
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getCode(), ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        Order order = orderService.findOrderByOrderNo(orderNo);
        if (order == null) {
            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getCode(), ErrorEnum.ORDER_NOT_EXIST.getMsg());
        }
        String phone =StringUtils.EMPTY;
        if (order.getHasPartner()!=null
                &&order.getHasPartner()==1){
            User user = userService.getById(order.getUserId());
            if (user != null){
                phone = user.getPartnerPhone();
            }
        }else{
            Address address = addressService.getById(order.getToAddressId());
            if (address!=null){
                phone = address.getPhone();
            }
        }
        if (StringUtils.isNotEmpty(phone)) {
            //更新
            MasterOrderAccitity accitity = accitityService.getMasterAccitityByOrderId(order.getId(), null);
            if (order.getType() == 1&&StringUtils.equals("1",acceptFlag)&&validateAccitity(accitity.getCurrentStatus(),MasterConstants.MasterOrderCurrentStatus.STATUS_5.getCode())) {
                accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_5.getCode());
                accitityService.updateAcctityById(accitity);
            }
            return JsonResult.success(phone);
        } else {
            return JsonResult.failure(ErrorEnum.USER_PHONE_NOT_FOUND.getCode(), ErrorEnum.USER_PHONE_NOT_FOUND.getMsg());
        }
    }

    @ApiOperation(value = "订单服务流程-发送收货验证码", notes = "发送收货验证码接口,参数{orderNo}必传")
    @PostMapping(value = "/sendTakeDelivery")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNumber", value = "收货人手机号码", required = false, dataType = "string"),
            @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "String")
    })
    public JsonResult sendTakeDelivery(@RequestParam(value = "phoneNumber") String phoneNumber,
                                       @RequestParam(value = "orderNo") String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        Order order = orderService.findOrderByOrderNo(orderNo);
        if (order == null) {
            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getMsg());
        }
        String phone = StringUtils.EMPTY;

        if (order.getHasPartner()!=null&&order.getHasPartner()==1){
            User user = userService.getById(order.getUserId());
            if (user !=null){
                phone = user.getPartnerPhone();
            }
        }else{
            Address address = addressService.getById(order.getToAddressId());
            phone = address.getPhone();
        }
        if (StringUtils.isEmpty(phone)) {
            return JsonResult.failure(ErrorEnum.RECIPT_MESSAGE_NOT_EXIST.getMsg());
        }
        if (phone.indexOf(" ")>0){
            phone = phone.replace(" ","");
        }
        //发送验证码
        Map<String,Object> templateParams = new HashMap<>();
        templateParams.put("verifyCode",order.getVerifyCode());
        if (smsSendService.sendRecVerifyCode(phone,templateParams)) {
            return JsonResult.success();
        } else {
            return JsonResult.failure(ErrorEnum.VERIFY_CODE_SEND_ERROR.getCode(),
                    ErrorEnum.VERIFY_CODE_SEND_ERROR.getMsg());
        }
    }

    @ApiOperation(value = "订单服务流程-收货验证(收货验证码验证)", notes = "收货验证(收货验证码验证)")
    @PostMapping(value = "/verificationOfReceipt")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "string"),
            @ApiImplicitParam(name = "verifyCode", value = "短信验证码", required = true, dataType = "String")
    })
    public JsonResult verificationOfReceipt(
            @RequestParam(value = "orderNo") String orderNo,
            @RequestParam(value = "verifyCode") String verifyCode) {
        String phone = StringUtils.EMPTY;
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        Order order = orderService.findOrderByOrderNo(orderNo);
        if (order == null) {
            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getMsg());
        }
        if (order.getHasPartner()!=null&&order.getHasPartner()==1){
            User user = userService.getById(order.getUserId());
            if (user !=null){
                phone = user.getPartnerPhone();
            }
        }else{
            Address address = addressService.getById(order.getToAddressId());
            phone = address.getPhone();
        }
        //发送验证码
        MasterOrderAccitity accitity = accitityService.getMasterAccitityByOrderId(order.getId(), null);
        if ( order.getVerifyCode()!=null && order.getVerifyCode().equals(verifyCode)&&validateAccitity(accitity.getCurrentStatus(),MasterConstants.MasterOrderCurrentStatus.STATUS_8.getCode())) {
            //更新
            accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_8.getCode());
            accitity.setAcctityStatus(MasterConstants.MasterAcctityStatus.ACCTITY_STATUS_3.getCode());
            if (accitityService.updateAcctityById(accitity)) {
                successOperate(order,verifyCode);
            }
            return JsonResult.success();
        } else {
            return JsonResult.failure(ErrorEnum.VERIFY_CODE_VALID_ERROR.getCode(),
                    ErrorEnum.VERIFY_CODE_VALID_ERROR.getMsg());
        }
    }

    /**
     * 订单完成操作
     * @param order
     * @param verifyCode
     */
    private void successOperate(Order order,String verifyCode){
        order.setStatus(Constant.OrderStatusEnum.WAIT_EVLAUTE.getCode());
        order.setUpdateAt(new Date());
        if (orderService.updateOrderById(order)){
            //
            updateMasterScoreDetail(order,CONSTANTS_1,true);
            //计算收益
            Map<String,BigDecimal> incomeMap = getOrderIncome(order.getOrderNo());
            //收益加入余额
            User user = userService.getById(getUserId());
            if (user != null){
                BigDecimal accountBalance = user.getAccountBalance().add(incomeMap.get("master"));
                BigDecimal goodAmount = order.getGoodsAmount()==null?BigDecimal.ZERO:order.getGoodsAmount();
                if (goodAmount.compareTo(BigDecimal.ZERO)==1){
                    //随意购金额
                     accountBalance = accountBalance.add(goodAmount);
                     insertAccountDetail(String.valueOf(goodAmount),getUserId(),"随意购代付款",CONSTANTS_1,order.getOrderNo(),"10",accountBalance);
                }
                user.setAccountBalance(accountBalance);
                if (userService.modifyById(user)){
                    insertAccountDetail(String.valueOf(incomeMap.get("master")),getUserId(),"订单收益",CONSTANTS_1,order.getOrderNo(),CONSTANTS_1,accountBalance);
                }
                if(order.getCollectionAmount()!=null
                        &&order.getCollectionAmount().compareTo(BigDecimal.ZERO)==1
                        &&order.getCollectionPayStatus()==2){
                    User user1 = userService.getById(order.getUserId());
                    logger.info("用户"+user1.getId()+"待收货款余额为{}",JSON.toJSONString(user1.getCollectBal()));
                    BigDecimal userAccountBalance = user1.getCollectBal().add(order.getCollectionAmount());
                    user1.setCollectBal(userAccountBalance);
                    //贷后货款
                    if (userService.modifyById(user1)){
                        logger.info("代收货款余额更新成功:"+DateUtil.dateToString(new Date(),"yyyy-MM-dd"),JSON.toJSONString(userAccountBalance));
                        insertAccountDetail(String.valueOf(order.getCollectionAmount()),order.getUserId(),"代收货款","2",order.getOrderNo(),CONSTANTS_1,userAccountBalance);
                    }
                }

            }


            //记录分站收益  azy
            SysAgent agent = agentService.getById(order.getAgentId());
            insertAgentAccountDetail(order.getAgentId(),Constant.AgentAccountTranTypeEnum.PERCENTAGE.getCode().toString(),
                    order.getOrderNo()+"订单抽成",incomeMap.get("agent"),agent.getBalance(),order.getOrderNo());
            agentService.updateBalance(order.getAgentId(),Constant.InOutEnum.IN.getCode().toString(),incomeMap.get("agent"));
            //是否存在保费
            if(order.getInsuranceFee()!=null&&order.getInsuranceFee().compareTo(BigDecimal.ZERO)>0){
                insertAgentAccountDetail(order.getAgentId(),Constant.AgentAccountTranTypeEnum.INSURE.getCode().toString(),
                        order.getOrderNo()+"保费收入",order.getInsuranceFee(),agent.getBalance().add(incomeMap.get("agent")),order.getOrderNo());
                agentService.updateBalance(order.getAgentId(),Constant.InOutEnum.IN.getCode().toString(),order.getInsuranceFee());
            }

            //记录平台收益
            SysAgent sysAgent = agentService.getById(Constant.DEFAULT_AGENT_ID);
            insertAgentAccountDetail(Constant.DEFAULT_AGENT_ID,Constant.AgentAccountTranTypeEnum.PERCENTAGE.getCode().toString(),
                    order.getOrderNo()+"订单抽成",incomeMap.get("sys"),sysAgent.getBalance(),order.getOrderNo());
            agentService.updateBalance(Constant.DEFAULT_AGENT_ID,Constant.InOutEnum.IN.getCode().toString(),incomeMap.get("sys"));
            UserMaster master = masterService.getUserMasterByUserId(order.getMasterId());
            String append = getOrderTypeAppend(order.getAgentId(),order.getType(),order.getChildType(),String.valueOf(order.getHasPartner()==null?0:order.getHasPartner())) + ","+master.getMasterName().substring(0,1);
           if (order.getType()==1){
               parsePushData(order,"订单完成","订单状态通知","【阿四服务】 " + append+"师傅已送达，别忘评价，你的评价是我们的进步！");
           }else{
               parsePushData(order,"订单完成","订单状态通知","【阿四服务】 " + append+"已完成服务别忘评价，你的评价是我们的进步！");
           }
        }
    }

    @ApiOperation(value = "订单服务流程-取货/技术服务照片上传", notes = "订单服务流程-取货图片上传")
    @PostMapping("/uploadGoodsPic")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParam(name = "uploadGoodsPicReq", value = "uploadGoodsPicReq实体", required = true, dataType = "UploadGoodsPicReq")
    public JsonResult<UploadImgResp> uploadGoodsPic(@Valid @RequestBody UploadGoodsPicReq uploadGoodsPicReq) {
        if (uploadGoodsPicReq.getPicBase64() == null || uploadGoodsPicReq.getPicBase64().size() <= 0) {
            return JsonResult.failure(ErrorEnum.PICTURE_PARAM_EMPTY.getCode(), ErrorEnum.PICTURE_PARAM_EMPTY.getMsg());
        }
        List<UploadImgResp> pics = uploadService.batchUpload(uploadGoodsPicReq.getPicBase64(), getUserId());
        String pic = StringUtils.EMPTY;
        if (CollectionUtils.isNotEmpty(pics)) {
            for (UploadImgResp resp : pics) {
                pic += resp.getName() + ",";
                logger.info("上传文件【"+uploadGoodsPicReq.getOrderNo()+"】:{}", JSON.toJSONString(resp));
            }
            Order order = orderService.findOrderByOrderNo(uploadGoodsPicReq.getOrderNo());
            if (order != null) {
                order.setGoodsImages(pic);
                //更新
                MasterOrderAccitity accitity = accitityService.getMasterAccitityByOrderId(order.getId(), null);
                String accCurStatusOld = accitity.getCurrentStatus();
                if (order.getType() == 1) {
                    switch (order.getChildType()) {
                        case 11:
                        case 12:
                            accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_4.getCode());
                            break;
                        case 13:
                            accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_5.getCode());
                            break;
                        default:
                            break;
                    }
                    order.setStatus(Constant.OrderStatusEnum.SENDING.getCode());
                } else {
                    order.setImages(pic);
                    if (order.getPriceWay()!=null&&order.getPriceWay()!=1){
                        //不定价扫码支付
                        accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_QRCODE.getCode());
                    }else{
                        //定价不扫码
                        accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_7.getCode());
                    }
                }
                accitity.setAcctityStatus(MasterConstants.MasterAcctityStatus.ACCTITY_STATUS_2.getCode());
                if (validateAccitity(accCurStatusOld,accitity.getCurrentStatus())){
                    Boolean flag = accitityService.updateAcctityById(accitity);
                    //订单流程改为送货中
                    if (flag){
                        flag = orderService.updateOrderById(order);
                        if (flag){
                            UserMaster master = masterService.getUserMasterByUserId(getUserId());
                            String statusAppend= getOrderTypeAppend(order.getAgentId(),order.getType(),order.getChildType(),String.valueOf(order.getHasPartner()==null?0:order.getHasPartner())) + ","+master.getMasterName().substring(0,1);
                            if (String.valueOf(order.getType()).equals("1")){
                                parsePushData(order,"订单开始服务","订单状态通知","【阿四服务】 " + statusAppend+"师傅已取货！");
                            }else{
                                parsePushData(order,"订单开始服务","订单状态通知","【阿四服务】 " + statusAppend+"师傅开始服务！");

                            }
                        }
                    }
                }
            } else {
                return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getCode(), ErrorEnum.ORDER_NOT_EXIST.getMsg());
            }
        }

        return JsonResult.success(pics);
    }

    @ApiOperation(value = "订单服务流程-取货/技术服务照片上传(上传文件)", notes = "订单服务流程-取货图片(content-type为multipart/form-data)")
    @PostMapping("/uploadGoodsPicFile")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "图片文件", required = true),
            @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "String")
    })    public JsonResult<List<UploadImgResp>> uploadGoodsPicFile(@RequestParam("file") MultipartFile[] file,@RequestParam("orderNo")String orderNo) {
        List<UploadImgResp> uploadImgResps =new ArrayList<>();
        String pics = StringUtils.EMPTY;
        String accOldStatus = StringUtils.EMPTY;
        if (StringUtils.isNotEmpty(orderNo)){
            Order order = orderService.findOrderByOrderNo(orderNo);
            //
            if (order == null) {
                return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getMsg());
            }
            //上传文件
            if (file!=null&&file.length>0){
                for (MultipartFile file1:file) {
                    UploadImgResp imgResp = uploadService.uploadImg(file1,getUserId());
                    if (imgResp!=null&&StringUtils.isNotEmpty(imgResp.getName())){
                        uploadImgResps.add(imgResp);
                        logger.info("上传文件【"+orderNo+"】:{}", JSON.toJSONString(uploadImgResps));
                        pics+=imgResp.getName()+",";
                    }
                }
            }
            MasterOrderAccitity accitity = accitityService.getMasterAccitityByOrderId(order.getId(), null);
            accOldStatus = accitity.getCurrentStatus();
            if (order.getType() == 1) {
                order.setGoodsImages(pics);
                switch (order.getChildType()) {
                    case 11:
                    case 12:
                        accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_4.getCode());
                        break;
                    case 13:
                        accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_5.getCode());
                        break;
                    default:
                        break;
                }
                order.setStatus(Constant.OrderStatusEnum.SENDING.getCode());
            } else {
                order.setImages(pics);
                if (order.getPriceWay()!=null
                        &&order.getPriceWay()!=1){
                    //不定价扫码支付
                    accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_QRCODE.getCode());
                    //不定价服务开始计时
                    accitity.setStartTime(new Date());
                }else{
                    //定价不扫码
                    accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_7.getCode());
                }
            }
            accitity.setAcctityStatus(MasterConstants.MasterAcctityStatus.ACCTITY_STATUS_2.getCode());
            if (validateAccitity(accOldStatus,accitity.getCurrentStatus())){
                if (accitityService.updateAcctityById(accitity)) {
                    //订单流程改为送货中

                    if (orderService.updateOrderById(order)){
                        logger.info("上传图片更新订单表【"+orderNo+"】成功:{}",JSON.toJSONString(order));
                        UserMaster master = masterService.getUserMasterByUserId(getUserId());
                        String statusAppend= getOrderTypeAppend(order.getAgentId(),order.getType(),order.getChildType(),String.valueOf(order.getHasPartner()==null?0:order.getHasPartner())) + ","+master.getMasterName().substring(0,1);
                        if (order.getType()==1){
                            parsePushData(order,"订单开始服务","订单状态通知","【阿四服务】 " + statusAppend+"师傅已取货！");
                        }else{
                            parsePushData(order,"订单开始服务","订单状态通知","【阿四服务】 " + statusAppend+"师傅开始服务！");

                        }

                    }
                }
            }
        }
        return JsonResult.success(uploadImgResps);
    }


    @ApiOperation(value = "订单服务流程-查看货物图片", notes = "订单服务流程-查看货物图片")
    @PostMapping("/viewGoodsPic/{orderNo}")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    public JsonResult<UploadImgResp> uploadGoodsPic(@PathVariable String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getCode(), ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        Order order = orderService.findOrderByOrderNo(orderNo);
        if (order == null) {
            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getCode(), ErrorEnum.ORDER_NOT_EXIST.getMsg());
        }
        String goodsPic = StringUtils.EMPTY;
        if (order.getType()==1){
            goodsPic = order.getGoodsImages();
        }else{
            goodsPic = order.getImages();
        }
        if (StringUtils.isEmpty(goodsPic)) {
            return JsonResult.failure(ErrorEnum.PICTURE_GOODS_EMPTY.getCode(), ErrorEnum.PICTURE_GOODS_EMPTY.getMsg());
        }
        String[] args = goodsPic.split(",");
        if (args != null && args.length > 0) {
            return JsonResult.success(uploadService.getPicUrl(args));
        } else {
            return JsonResult.failure(ErrorEnum.PICTURE_GOODS_EMPTY.getCode(), ErrorEnum.PICTURE_GOODS_EMPTY.getMsg());
        }
    }


    @ApiOperation(value = "订单服务流程-已到达送货地", notes = "已到达送货地接口(帮我取，帮我送，随意购流程)")
    @PostMapping(value = "/inDeliverAddress")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, dataType = "String")
    public JsonResult inDeliverAddress(@RequestParam("orderNo") String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        Order order = orderService.findOrderByOrderNo(orderNo);
        if (order == null) {
            return JsonResult.failure(ErrorEnum.ORDER_NOT_EXIST.getCode(), ErrorEnum.ORDER_NOT_EXIST.getMsg());
        }
        Date now  = new Date();
        MasterOrderAccitity accitity = accitityService.getMasterAccitityByOrderId(order.getId(), null);
        String accOldStatus = accitity.getCurrentStatus();
        order.setOperatorFinal(0);
        order.setFinalTime(now);
        if (order.getType() == 1) {
            switch (order.getChildType()) {
                case 11:
                    if(order.getHasPartner()!=null&&order.getHasPartner()==1){
                        accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_8.getCode());
                        accitity.setAcctityStatus(MasterConstants.MasterAcctityStatus.ACCTITY_STATUS_3.getCode());
                    }else{
                        if (order.getCollectionAmount()!=null&&order.getCollectionAmount().compareTo(BigDecimal.ZERO)==1){
                            accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_6.getCode());
                        }else{
                            accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_7.getCode());
                        }
                    }
                    break;
                case 12:
                case 13:
                    accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_7.getCode());
                    break;
                default:
                    break;
            }

        }else{
//            accitity.setAcctityStatus(MasterConstants.MasterAcctityStatus.ACCTITY_STATUS_2.getCode());
            accitity.setCurrentStatus(MasterConstants.MasterOrderCurrentStatus.STATUS_3.getCode());
        }
        if (validateAccitity(accOldStatus,accitity.getCurrentStatus())){
            boolean flag =  accitityService.updateAcctityById(accitity);
            //合作商家订单完成
            if (order.getHasPartner()!=null&&order.getHasPartner()==1&&flag){
                order.setFinishStatus(0);
                successOperate(order,"");
            }else{
                //发送短信，推送消息
                orderService.updateOrderById(order);
//                JsonResult smsResult = sendTakeDelivery("",orderNo);
                String verifyCode = order.getVerifyCode();
                sysMessageService.saveMessage("服务确认码", "您本次服务的确认码为【"+verifyCode+"】", true, order.getUserId());
            }
        }
        return JsonResult.success();
    }



    /************************************订单服务流程end********************************************/

    /************************************我的钱包start********************************************/
    @ApiOperation(value = "更多-历史订单（标题信息）", notes = "历史订单接口")
    @GetMapping(value = "/historyTitle")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    public JsonResult<HistoryOrderResp> historyTitle() {
        HistoryOrderResp historyOrderResp = new HistoryOrderResp();
        HistoryOrderResp orderResp = orderService.getHistoryOrderNum(getUserId());
        List<Integer> statusList = new ArrayList<>();
        statusList.add(Constant.OrderStatusEnum.SENDING.getCode());
        statusList.add(Constant.OrderStatusEnum.SERVERING.getCode());
        statusList.add(Constant.OrderStatusEnum.FETCHING.getCode());
        List<OrderNear> orderNears = orderService.getOrderByStatusList(getUserId(),statusList);
        UserMaster master = masterService.getUserMasterByUserId(getUserId());
        BigDecimal expComeCount = new BigDecimal(0);
        double expCome = 0l;
        if (CollectionUtils.isNotEmpty(orderNears)){
            for (OrderNear near:orderNears) {
                expCome=  expComeCount.add(getIncome(near.getOrderNo())).doubleValue();

            }
        }
        orderResp.setExpIncome(String.valueOf(expCome));
        return JsonResult.success(orderResp);
    }


    @ApiOperation(value = "更多-历史订单（完成）", notes = "历史订单接口")
    @GetMapping(value = "/historyOrderOK")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    public JsonResult<OrderNearResp> historyOrderOK(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM + "") int pageNum,
                                                    @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE + "") int pageSize) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(Constant.OrderStatusEnum.OK.getCode());
        integerList.add(Constant.OrderStatusEnum.WAIT_EVLAUTE.getCode());
        PageInfo<OrderNearResp> orderNearPageInfo = orderService.findOrderByStatusPage(integerList, getUserId(), pageNum, pageSize);
        if (CollectionUtils.isNotEmpty(orderNearPageInfo.getList())){
            orderNearPageInfo.getList().forEach(item->{
                item.setExpectedIncome(String.valueOf(getIncome(item.getOrderNo())));
            });
        }
        return JsonResult.success(orderNearPageInfo);
    }

    @ApiOperation(value = "更多-历史订单(已取消)", notes = "历史订单接口")
    @GetMapping(value = "/historyOrderCancel")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    public JsonResult<OrderNearResp> historyOrderCancel(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM + "") int pageNum,
                                                        @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE + "") int pageSize) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(Constant.OrderStatusEnum.CANCLE.getCode());
        PageInfo<OrderNearResp> orderNearPageInfo = orderService.findOrderByStatusPage(integerList, getUserId(), pageNum, pageSize);
        if (CollectionUtils.isNotEmpty(orderNearPageInfo.getList())){
            orderNearPageInfo.getList().forEach(item->{
                item.setExpectedIncome(String.valueOf(getIncome(item.getOrderNo())));
            });
        }
        return JsonResult.success(orderNearPageInfo);
    }

    @ApiOperation(value = "更多-历史订单详情", notes = "历史订单详情接口,参数{orderNo订单号}必传")
    @PostMapping(value = "/historyOrderDetails/{orderNo}")
    @PreAuthorize("hasRole('ROLE_MASTER')")
    public JsonResult<OrderNear> historyOrderDetails(@PathVariable String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return JsonResult.failure(ErrorEnum.ORDER_NO_EMPTY.getMsg());
        }
        Long userId = getUserId();
        OrderNear orderNear = new OrderNear();
        List<OrderNear> orderNears = orderService.findOrderByStatus(null, userId, orderNo, null);
        if (CollectionUtils.isNotEmpty(orderNears)) {
            orderNear = orderNears.get(0);
            orderNear.setExpectedIncome(String.valueOf(getIncome(orderNear.getOrderNo())));
            orderNears.forEach(item->{
                if(item.getImages() != null){
                    //处理图片
                    List<String> images = new ArrayList<String>();
                    Arrays.stream(Optional.ofNullable(item.getImages()).get().split(",")).forEach(o->{
                        images.add(componentUtil.convertImgUrl(o));
                    });
                    item.setImagesList(images);
                }
                if(item.getGoodsImages() != null){
                    //处理图片
                    List<String> images = new ArrayList<String>();
                    Arrays.stream(Optional.ofNullable(item.getGoodsImages()).get().split(",")).forEach(o->{
                        images.add(componentUtil.convertImgUrl(o));
                    });
                    item.setGoodsImagesList(images);
                }
                //处理音频
                Optional.ofNullable(item.getAudio()).ifPresent(o->item.setAudio(componentUtil.convertImgUrl(o)));
            });
        }
        return JsonResult.success(orderNear);
    }
    /************************************我的钱包end********************************************/



    private MasterTitleMessageResp getMasterTitileDetails(UserMaster user, MasterTitleMessageResp resp) {
        //今日完成总数
        List<Integer> statusList = new ArrayList<>();
        statusList.add(Constant.OrderStatusEnum.WAIT_EVLAUTE.getCode());
        statusList.add(Constant.OrderStatusEnum.OK.getCode());
        Date date = new Date();
        List<OrderNear> orderNears = orderService.findOrderByStatusListCurDate(user.getUserId(), statusList,date);
        resp.setOrderNum(String.valueOf(orderNears.size()));
        //师傅收益
        UserMaster master = masterService.getUserMasterByUserId(user.getUserId());
        //获取今日订单
//        List<OrderNear> orderNears = orderService.getOrderByStatusList(user.getId(),statusList);
        //获取收益比例
        BigDecimal IncomeCount = new BigDecimal(0);
        double income = 0l;
        if (CollectionUtils.isNotEmpty(orderNears)) {
            for (OrderNear near : orderNears) {
                if (StringUtils.isEmpty(near.getAmount())){
                    near.setAmount(CONSTANTS_0);
                }
                income += IncomeCount.add(getIncome(near.getOrderNo())).setScale(2,BigDecimal.ROUND_HALF_DOWN).doubleValue();
            }
        }
        resp.setInCome(String.valueOf(income));
        BigDecimal expComeCount = new BigDecimal(0);
        double expCome = 0l;
        //预计收益
        statusList = new ArrayList<>();
        statusList.add(Constant.OrderStatusEnum.SENDING.getCode());
        statusList.add(Constant.OrderStatusEnum.SERVERING.getCode());
        statusList.add(Constant.OrderStatusEnum.FETCHING.getCode());
        List<OrderNear> extrOrderNear = orderService.findOrderByStatusListCurDate(user.getUserId(), statusList,null);
        if (CollectionUtils.isNotEmpty(extrOrderNear)) {
            for (OrderNear near : extrOrderNear) {
                expCome=  expComeCount.add(getIncome(near.getOrderNo())).setScale(2,BigDecimal.ROUND_HALF_DOWN).doubleValue();

            }
        }
        resp.setExpectedInCome(String.valueOf(expCome));
        resp.setScore(StringUtils.isNotEmpty(master.getScore())?master.getScore():CONSTANTS_0);
        return resp;
    }

    private BigDecimal getIncome(String orderNo) {

        return getOrderIncome(orderNo).get("master");
    }

    /**
     * 查询用户、分站、总台收入 azy
     * @param orderNo
     * @return
     */
    private Map<String,BigDecimal> getOrderIncome(String orderNo) {
        return orderService.getIncome(orderNo);

    }




    private void initPageParam(Integer pageNum, Integer pageSize, MasterReq masterReq, MasterServicedReq masterServicedReq) {
        if (pageNum == null || pageNum == 0) {
            pageNum = PageConstants.PAGE_NUM;
        }
        if (pageSize == null || pageSize == 0) {
            pageSize = PageConstants.PAGE_SIZE;
        }
        if (masterReq == null) {
            masterServicedReq.setPageNum(pageNum);
            masterServicedReq.setPageSize(pageSize);
        } else {
            masterReq.setPageNum(pageNum);
            masterReq.setPageSize(pageSize);
        }
    }

    private String time(String order,String arriveFlag,UserMaster master,Date taskTime){
        List<OrderNear> orderNears =  orderService.findOrderByStatus(null, null, order,null);
        if (CollectionUtils.isNotEmpty(orderNears)){
            OrderNear orderNear = orderNears.get(0);
            if (!"实时".equals(orderNear.getHasInstantDesc())){
                if (taskTime != null){
                    String  ms =  DateUtil.getDatePoor(taskTime,new Date());
//                    long ms = day/24*60*60;
                    return ms;
                }else{
                    return 15*60+"";
                }
            }
            if (CONSTANTS_1.equals(arriveFlag)){
                Double distanc = 0D;
                if (StringUtils.isNotEmpty(orderNear.getFromLongitude())
                        &&StringUtils.isNotEmpty(orderNear.getFromLatitude())){
                    distanc = DistanceUtil.getDistance(Double.parseDouble(master.getLatitude()),
                            Double.parseDouble(master.getLongitude()),Double.parseDouble(orderNear.getFromLatitude()!=null?orderNear.getFromLatitude():orderNear.getToLatitude()),
                            Double.parseDouble(orderNear.getFromLongitude()!=null?orderNear.getFromLongitude():orderNear.getToLongitude()));
                }
                return DistanceUtil.arrivedTime(distanc,6D);
            }else{
                Double distanc = 0D;
                if (StringUtils.isNotEmpty(orderNear.getFromLongitude())
                        &&StringUtils.isNotEmpty(orderNear.getFromLatitude())){
                    distanc = DistanceUtil.getDistance(Double.parseDouble(orderNear.getToLongitude()),
                            Double.parseDouble(orderNear.getToLongitude()),Double.parseDouble(orderNear.getToLatitude()),
                            Double.parseDouble(orderNear.getToLongitude()));
                }
                return DistanceUtil.arrivedTime(distanc,6D);
            }
        }
        return CONSTANTS_0;
    }

    /**
     * 当前流程与更新流程判断
     * @param currentStatus
     * @param updateStatus
     * @return
     */
    private boolean validateAccitity(String currentStatus,String updateStatus){
        Integer currentInt = Integer.parseInt(currentStatus);
        Integer updateInt = Integer.parseInt(updateStatus);
        if (currentInt>updateInt){
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    @Async
    public void updateMasterScoreDetail(Order order,String scoreType,Boolean completeScore){
        Long scor_e = 0l;
        if (order.getNightFee()!=null){
            Long score = scoreManagentmentService.computingScore(Long.parseLong(order.getAgentId()),null,false,false,true,false,false,false,false);
            if (score!=null&&score>0l){
                insertScore(order.getMasterId(),"深夜服务奖励",order.getOrderNo(),String.valueOf(score),"奖励");
            }
            scor_e +=score;
        }
        if (order.getOtherFee()!=null){
            Long score = scoreManagentmentService.computingScore(Long.parseLong(order.getAgentId()),null,false,true,true,false,false,false,false);
            if (score!=null&&score>0l){
                insertScore(order.getMasterId(),"特殊天气奖励",order.getOrderNo(),String.valueOf(score),"奖励");
            }
            scor_e +=score;
        }
        HistoryOrderResp count = orderService.getHistoryOrderNum(order.getMasterId());
        if (Integer.parseInt(count.getCurrentWeekNum())>0){
            Long score = scoreManagentmentService.computingScore(Long.parseLong(order.getAgentId()),Integer.parseInt(count.getCurrentWeekNum()),false,false,false,false,false,false,false);
            if (score!=null&&score!=0){
                insertScore(order.getMasterId(),"订单达标数奖励",order.getOrderNo(),String.valueOf(score),"奖励");

            }
        }
        if (completeScore){
            Long score = scoreManagentmentService.computingScore(Long.parseLong(order.getAgentId()),Integer.parseInt(count.getCurrentWeekNum()),false,false,false,false,false,false,true);
            if (score!=null&&score!=0){
                insertScore(order.getMasterId(),"完成订单",order.getOrderNo(),String.valueOf(score),"奖励");

            }
            scor_e +=score;
        }
        UserMaster master1 = masterService.getUserMasterByUserId(order.getMasterId());
        if (master1!=null){
            Integer scores =  Integer.parseInt(StringUtils.isNotEmpty(master1.getScore())?master1.getScore():CONSTANTS_0)+Integer.parseInt(String.valueOf(scor_e));
            master1.setScore(String.valueOf(scores));
            //计算星级
            String star = scoreManagentmentService.parseStar(Long.parseLong(String.valueOf(scores)));
            master1.setMasterStars(star);
            masterService.saveOrUpdate(master1,false);
        }

    }

    private String getMasterStar(Long massterId){
        UserMaster master = masterService.getUserMasterByUserId(massterId);

        String star =  scoreManagentmentService.parseStar(Long.parseLong(master.getScore()));
        if (StringUtils.isNotEmpty(star)){
            return star;
        }
        return "0";
    }


    public void updateDispatch(Long orderId,boolean falg){
        OrderDispatch dispatch = orderDispatchService.getByOrderId(orderId);
        logger.info("更新派单表状态:{}",falg);
        if (dispatch !=null){
            if (falg){
                //true同意
                dispatch.setStatus(2);
            }else{
                dispatch.setStatus(3);
            }
            if (orderDispatchService.updateOrderDispatch(dispatch)){
                logger.info("派单表更新成功:{}",dispatch.getOrderNo());
            }else{
                logger.info("派单表更新失败:{}",dispatch.getOrderNo());
            }
        }
    }


    public void insertAccountDetail(String income,Long userId,String tranDesc,String accountType,String orderNo,String inOutType,BigDecimal accountBalance){
        try {
            UserAccountDetail accountDetail = new UserAccountDetail();
            accountDetail.setAccountType(accountType);
            accountDetail.setAccoutWay(4L);
            accountDetail.setDetailType("2");
            accountDetail.setAmount(String.valueOf(income));
            accountDetail.setInOutType(inOutType);
            accountDetail.setTranDesc(tranDesc);
            accountDetail.setStatus(CONSTANTS_0);
            accountDetail.setCreateDt(new Date());
            accountDetail.setUpdateDt(new Date());
            accountDetail.setUserId(userId);
            accountDetail.setOutTradeNo(orderNo);
            accountDetail.setTranAmount(accountBalance);
            accountDetailService.save(accountDetail);
        }catch (Exception ex){
            System.out.println("插入账户明细表异常");
        }
    }

    @Async
    public void insertAgentAccountDetail(String agentId,String tranType,String desc,BigDecimal income,BigDecimal bal,String orderNo){
        try {
            AgentAccountDetail accountDetail = new AgentAccountDetail();
            accountDetail.setAgentId(agentId);
            accountDetail.setTranType(tranType);
            accountDetail.setTranBal(bal.add(income));
            accountDetail.setAmount(income);
            accountDetail.setInOut(CONSTANTS_1);//收入
            accountDetail.setTranDesc(desc);
            accountDetail.setTranTime(new Date());
            accountDetail.setTranId(orderNo);
            agentAccountDetailService.save(accountDetail);
        }catch (Exception ex){
            System.out.println("插入账户明细表异常");
        }
    }


    @Async
    public void insertScore(Long userId,String desc,String orderNo,String score,String scoreType){
        MasterScoreDetails details = new MasterScoreDetails();
        Date now = new Date();
        details.setCreateDate(now);
        details.setOrderNo(orderNo);
        details.setScoreType(scoreType);
        details.setScore(String.valueOf(score));
        details.setScoreDes(desc);
        details.setUserId(userId);
        detailsService.save(details);
    }

    public void parsePushData(Order order,String status,String title,String content){
        try {
            Map<String,Object> pramMap = new HashMap<>();
            User user = userService.getById(order.getUserId());
            String type = StringUtils.EMPTY;
            String fromAddress = StringUtils.EMPTY;
            String toAddress = StringUtils.EMPTY;
            String phone = StringUtils.EMPTY;
            String masterName = StringUtils.EMPTY;
            if (order.getHasPartner()==1){
                type = "合作商家";
                toAddress = user.getPartnerAddress();
            }else{
                type = orderService.getChildTypeOrTypeDesc(String.valueOf(order.getType()),String.valueOf(order.getChildType()),order.getAgentId());
                if (order.getFromAddressId()!=null&&order.getFromAddressId()!=0){
                    Address  address = addressService.getById(order.getFromAddressId());
                    fromAddress = Optional.ofNullable(address).map(address1 -> address1.getTitle()).get();
                }
                if (order.getToAddressId()!=null&&order.getToAddressId()!=0){
                    Address  address = addressService.getById(order.getToAddressId());
                    toAddress = Optional.ofNullable(address).map(address1 -> address1.getTitle()).get();
                }
            }
            List<MasterMessage> message = masterService.findAllMasterMessage(order.getMasterId());
            if (CollectionUtils.isNotEmpty(message)){
                MasterMessage mMessage = message.get(0);
                phone = mMessage.getPhone();
                masterName = mMessage.getMasterName();
            }
            pramMap.put("keyword1", AppletsTemplateData.valueOf(type));
            pramMap.put("keyword2",AppletsTemplateData.valueOf(status));
            pramMap.put("keyword3",AppletsTemplateData.valueOf(fromAddress));
            pramMap.put("keyword4",AppletsTemplateData.valueOf(toAddress));
            pramMap.put("keyword5",AppletsTemplateData.valueOf(masterName));
            pramMap.put("keyword6",AppletsTemplateData.valueOf(phone));
            logger.info("订单推送发送start",order.getOrderNo());
            sysMessageService.saveAndPushMessage(title,content,order.getUserId(),pramMap, AppletsPushTemplateEnum.ORDER_STATUS_CHANGE);
            logger.info("订单推送发送end",order.getOrderNo());

        }catch (Exception ex){
            logger.info("推送异常订单编号【"+order.getOrderNo()+"】:{}",ex);
        }
    }
}
